﻿#region ... Copyright Notice ...
/*
   Copyright 2006-2008 Provo Labs    http://www.provolabs.com

	Author: Tyler Jensen    http://www.tsjensen.com/blog
	Released by the author with written permission of Provo Labs

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Atrax.Html
{
	public class Statistics
	{
		public double GetAverage(double[] data)
		{
			int len = data.Length;
			if (len == 0) throw new Exception("No data");
			double sum = 0;
			for (int i = 0; i < data.Length; i++) sum += data[i];
			return sum / len;
		}

		public double GetVariance(double[] data)
		{
			int len = data.Length;
			double avg = GetAverage(data);
			double sum = 0;
			for (int i = 0; i < data.Length; i++) sum += System.Math.Pow((data[i] - avg), 2);
			return sum / (len-1);
		}

		public double GetStdev(double[] data)
		{
			return Math.Sqrt(GetVariance(data));
		}

		public void GetCorrelation(double[] x, double[] y, ref double covXY, ref double pearson)
		{
			if (x.Length != y.Length) throw new Exception("Length of sources is different");

			double avgX = GetAverage(x);
			double stdevX = GetStdev(x);
			double avgY = GetAverage(y);
			double stdevY = GetStdev(y);

			int len = x.Length;
			for (int i = 0; i < len; i++) covXY += (x[i] - avgX) * (y[i] - avgY);

			covXY /= len;
			pearson = covXY / (stdevX * stdevY);
		}
	}
}
